package org.example.demo.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.model.rememberScreenModel
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import coil3.compose.AsyncImage
import org.example.demo.bot.response.BotSimpleInfo
import org.example.demo.module.BotModule

class HomeScreen : Screen {

    @Composable
    override fun Content() {
        val navigator = LocalNavigator.currentOrThrow
        val botModule = rememberScreenModel { BotModule() }
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            modifier = Modifier.padding(8.dp)
        ) {
            items(botModule.bots.toList()) {
                BotItem(it) {
                    navigator.push(
                        ChatScreen(
                            iconUrl = it.iconUrl ?: "",
                            name = it.name ?: "",
                            botId = it.id ?: ""
                        )
                    )
                }
            }
        }
    }
}

@Composable
private fun BotItem(botSimpleInfo: BotSimpleInfo, onItemClick: () -> Unit) {
    Row(
        modifier = Modifier.padding(8.dp).size(300.dp, 120.dp).clickable {
            onItemClick()
        }
            .shadow(elevation = 4.dp, shape = RoundedCornerShape(8.dp))
            .background(color = Color.White, shape = RoundedCornerShape(8.dp))
            .border(width = 1.dp, color = Color.Gray, shape = RoundedCornerShape(8.dp)),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(modifier = Modifier.weight(4f).padding(12.dp)) {
            Text(text = botSimpleInfo.name ?: "")
            Text(text = botSimpleInfo.description ?: "")
        }
        AsyncImage(
            model = botSimpleInfo.iconUrl,
            contentDescription = null,
            modifier = Modifier.size(80.dp).padding(end = 12.dp)
        )
    }
}